package com.dc.di.ftpserver.database;

import java.util.Date;

import org.apache.ftpserver.ftplet.FtpFile;
import org.apache.log4j.Logger;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.util.UUIDUtil;

import com.dc.di.ftpserver.entity.AttachmentlogEntity;
import com.dc.di.ftpserver.logmanager.RecvLog;
import com.dc.di.ftpserver.util.Const;

public class AttachmentRecvDbLog implements RecvLog{
	private AttachmentLogManager aLogManager;
	private static final Logger logger = Logger.getLogger(AttachmentRecvDbLog.class);
	public AttachmentRecvDbLog()throws KettleException {
		this.aLogManager=AttachmentLogManager.getRecvInstance();
	}
	@Override
	public void saveRecvLog(String groupname,FtpFile file,String name)throws Exception{
		String filename=file.getName();
		String filepath = file.getAbsolutePath();
		filepath = filepath.substring(0,filepath.lastIndexOf(filename));
		if(name!=null){
			filename=name;
			if(logger.isDebugEnabled()){
				logger.debug("use ".concat(name).concat(" as the real filename"));
			}
		}else{
			if(logger.isDebugEnabled()){
				logger.debug("use default name from file");
			}
		}
		if(aLogManager.getDataId(groupname, filename, filepath)==null){
			AttachmentlogEntity attachLog = new AttachmentlogEntity();
			attachLog.setId(UUIDUtil.getUUIDAsString());
			attachLog.setGroupname(groupname);
			attachLog.setFilename(filename);
			attachLog.setFilepath(filepath);
			attachLog.setFilesize(0L);
			attachLog.setStarttime(new Date());
			attachLog.setFlag(Const.FLAG_START);
			aLogManager.insertRecvlog(attachLog);
		}else{
			if(logger.isDebugEnabled()){
				logger.debug(new StringBuilder("the attachmentrecvlog is exist:").append("groupname=").append(groupname)
						.append(",filename=").append(filename).append(",filepath=").append(filepath));
			}
		}
	}
	@Override
	public void updateRecvSuccessLog(String groupname,FtpFile file) throws Exception{
		updateRecvLog(groupname,file,Const.FLAG_END);
	}
	@Override
	public void updateRecvFailLog(String groupname,FtpFile file) throws Exception{
		updateRecvLog(groupname,file,Const.FLAG_FAIL);
	}
	public void updateRecvLog(String groupname,FtpFile file,String flag) throws Exception{
		String filename = file.getName();
		String filepath = file.getAbsolutePath();
		filepath = filepath.substring(0,filepath.lastIndexOf(filename));
		AttachmentlogEntity attachLog = new AttachmentlogEntity();
		attachLog.setGroupname(groupname);
		attachLog.setFilename(filename);
		attachLog.setFilepath(filepath);
		attachLog.setEndtime(new Date());
		attachLog.setFilesize(file.getSize());
		attachLog.setFlag(flag);
		aLogManager.updatelog(attachLog);
	}
}
